#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年12月13日

@author: chenyongbing
'''
import sys,os,datetime,json
from localConfig import baseLocalConfig
import time


import logging
current_dir = os.path.dirname(__file__)
import urllib2,urllib,re


class ZhimindWsDatas(object):
    '''
    classdocs
    '''


    def __init__(self,token='10002000',base = 'http://192.168.1.203:8080/zm-ws-3.0/api/v3/'):
        '''
        Constructor
        '''
        self.token = token
        self.base = base
    def getResponse(self,url,detailMap={},data=None,type='post',times=5):
        for i in range(times):
            if data==None:
                groupList = []
                listKeys = []
                for key,values in detailMap.iteritems():
                    if isinstance(values,list):
                        listKeys.append(key)
                        
                        #del detailMap[key]
                for lk in listKeys:
                    values = detailMap[lk]
                    del detailMap[lk]
                    count = 0
                    for value in values:
                        count+=1
                        detailMap[lk+'_'+str(count)] = value
                
                data=urllib.urlencode(detailMap)
                for lk in listKeys:
                    data = re.sub('%s_[\d]+'%lk,lk,data)
                
            else:
                data = data
            
            if type=='post':
                #data = 'Token=10002000&StartTime=2014-05-20&EndTime=2014-06-10&GroupType=4&Dimension=2&CustomerType=0&Group=32010226'
                #print url,data
                try:
                    req=urllib2.Request(url,data)
    #             print req
                    response=urllib2.urlopen(req)
                except:
                    time.sleep(5)
                    continue
            else:
                #print url+'?'+data
                while 1:
                    try:
                        response = urllib2.urlopen(url+'?'+data,timeout=5) 
                        break
                    except:
                        continue
            try:
                page=response.read()
            except:
                time.sleep(5)
                continue
            r = self.check_response(page, i)
            if r!=False:
                return page
                
        logging.error("WS Required Failed")
        sys.exit(1)
     
     
    def check_response(self,page='',times=0):

        try:
            rdatas = json.loads(page)

        except Exception,error:
            logging.error('WS Required Times %s Failed.'%times)
            return False
        code = rdatas['code']
        if code==1000:
            return rdatas
        else:
            return False
     
    def get_customer(self,startTime=None,endTime=None,comp_group=None,prov_group=None,city_group=None,group=None,type='customer_flow',timeType='all',groupType=4,customerType='all'):
        '''
            进店量,取接口:51.    客流趋势：关键指标  字段 EnteringCustomerFlow
            customer Type : all .deep .out
        '''
        if customerType == 'deep' or customerType == 'out':
            return self.get_customer_dur(startTime, endTime, comp_group, prov_group, city_group, group, rtype=customerType, groupType=groupType)
        if startTime==None and endTime==None:
            startTime = (datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
            endTime = startTime
        elif endTime==None:
            endTime =( datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
        if group:
            groupList = [str(group)]
            #groupType = 4
        elif city_group:
            groupList = [str(city_group)]
            #groupType = 2
        elif prov_group:
            groupList = [str(prov_group)]
            #groupType = 1
        elif comp_group:
            groupList = [str(comp_group)]
            #groupType = 0
        else:
            logging.error("You Must insert One Group.")
        logging.info('Get Data From Ws By startTime=%s,endTime=%s,GroupList=%s,GroupType=%s'%(startTime,endTime,','.join(groupList),groupType))
        
        paramap={'StartTime':startTime,'EndTime':endTime,'GroupList':groupList,'GroupType':groupType,'Token':self.token}
        url = self.base+'statis_customer/stats_keypoint'
        page = self.getResponse(url, paramap)
        #print page
        datas = json.loads(page)
        data = datas['DataList'][0]

        
    
        if type=='customer_flow':
            count = data['EnteringCustomerFlow']['Count']
            number = data['EnteringCustomerFlow']['Number']
            weekday_rate = data['EnteringCustomerFlow']['Weekday']
            weekend_rate =data['EnteringCustomerFlow']['Weekend']
            change = data['EnteringCustomerFlow']['Change']
            if change==None:change='-'
            if timeType=='all':
                return count,change
            elif timeType == 'week':
                return int(round(count*weekday_rate,0)),int(round(count*weekend_rate,0))

    def get_customer_dur(self,startTime=None,endTime=None,comp_group=None,prov_group=None,city_group=None,group=None,customerType=0,rtype='dur',groupType=4):
        '''
           
        '''
        if startTime==None and endTime==None:
            startTime = (datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
            endTime = startTime
        elif endTime==None:
            endTime =( datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
        if group:
            groupList = [str(group)]
            #groupType = 4
        elif city_group:
            groupList = [str(city_group)]
            #groupType = 2
        elif prov_group:
            groupList = [str(prov_group)]
            #groupType = 1
        elif comp_group:
            groupList = [str(comp_group)]
            #groupType = 0
        else:
            logging.error("You Must insert One Group.")
        logging.info('Get Data From Ws By startTime=%s,endTime=%s,GroupList=%s,GroupType=%s'%(startTime,endTime,','.join(groupList),groupType))
        
        paramap={'StartTime':startTime,'EndTime':endTime,'GroupList':groupList,'GroupType':groupType,'CustomerType':customerType,'Token':self.token}
        url = self.base+'statis_duration/statis_duration_keypoint'
        page = self.getResponse(url, paramap)
        #print page
        datas = json.loads(page)
        data = datas['DataList'][0]
        if rtype=='dur':
            avg_dur = data['DurationTime']
            return avg_dur
        else:
            
            deep_customer_count = data['DeepCustomerCount']
            deep_customer_count_change = data['DeepCustomerCountChange']
            out_customer_count = data['OutCustomerCount']
            out_customer_count_change = data['OutCustomerCountChange']
            if rtype=='deep':
                return deep_customer_count,deep_customer_count_change
            elif rtype == 'out':
                return out_customer_count,out_customer_count_change
            elif rtype == 'deep-out':
                return deep_customer_count,deep_customer_count_change,out_customer_count,out_customer_count_change
    
    def trend_rank_by_group(self,startTime=None,comp_group=None,prov_group=None,city_group=None,group=None,customerType=0,timeType=0,orderItem='',groupType=4):
        '''
            趋势排行
        '''
        if startTime==None:
            startTime = (datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
            timeType = 1
        orderType =1
        TotalPages = 0
        PageNumber=10
        CurrentPage =1
        if group:
            groupList = [str(group)]
            #groupType = 4
        
        elif city_group:
            groupList = [str(city_group)]
            #groupType = 2
        elif prov_group:
            groupList = [str(prov_group)]
            #groupType = 1
        elif comp_group:
            groupList = [str(comp_group)]
            #groupType = 0
        else:
            logging.error("You Must insert One Group.")
            
        paramap={'StartTime':startTime,'GroupList':groupList,'GroupType':groupType,
                 'RequestType':groupType,'TimeType':timeType,'OrderItem':orderItem,
                 'OrderType':orderType,'ToatlPages':TotalPages,'PageNumber':PageNumber,
                 'CurrentPage':CurrentPage,'Token':self.token}   
        url = self.base+'over_view/trend_rank_by_group'
        page = self.getResponse(url, paramap)
        #print page
        datas = json.loads(page)
        data = datas['DataList'][0]
        #print data

    def stats_visit_frequency_scatter(self,startTime=None,endTime=None,comp_group=None,prov_group=None,city_group=None,group=None,customerType=0,groupType=4):
        '''
            
        '''
        if startTime==None and endTime==None:
            startTime = (datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
            endTime = startTime
        elif endTime==None:
            endTime =( datetime.date.today()-datetime.timedelta(1)).strftime('%Y-%m-%d')
        if group:
            Group = str(group)
            #groupType = 4
        elif city_group:
            Group = str(city_group)
            #groupType = 2
        elif prov_group:
            Group = str(prov_group)
            #groupType = 1
        elif comp_group:
            Group = str(comp_group)
            #groupType = 0
        
        
        
        else:
            logging.error("You Must insert One Group.")
        logging.info('Get Data From Ws By startTime=%s,endTime=%s,Group=%s,GroupType=%s'%(startTime,endTime,Group,groupType))
        
        paramap={'StartTime':startTime,'EndTime':endTime,'Group':Group,'GroupType':groupType,'CustomerType':customerType,'Token':self.token}
        url = self.base+'statis_frequency/stats_visit_frequency_scatter'
        page = self.getResponse(url, paramap)
        #print page
        datas = json.loads(page)
        datas = datas['DataList']
        for data in datas:
            if data['Type']=='1':
                count_1=data['Count']
            if data['Type']=='2':
                count_2=data['Count']
            if data['Type']=='3':
                count_3=data['Count']
            if data['Type']=='4':
                count_4=data['Count']
        return count_1,count_2,count_3,count_4

        
        
if __name__ == '__main__':
    base = 'http://60.191.203.30:8080/zm-ws-3.0/api/v3/'
    myZhimindWsDatas = ZhimindWsDatas(base=base)
    #myZhimindWsDatas.trend_rank_by_group(startTime="2014-12-12", comp_group='32010464',orderItem='15')
    myZhimindWsDatas.get_customer_dur(startTime='2014-12-12', endTime='2014-12-12', comp_group='32010464', customerType=0)
    
    
    